const path = require('path')

const CompressionWebpackPlugin = require('compression-webpack-plugin')
const resolve = dir => path.join(__dirname, dir)

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production';

// page title
const name = 'vcf'
// 生产环境，测试和正式
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)

// 本地环境是否需要使用cdn
const devNeedCdn = false

// const {
//   HashedModuleIdsPlugin
// } = require('webpack');

// externals
const externals = {
  vue: 'Vue',
  'vue-router': 'VueRouter',
  vuex: 'Vuex',
  axios: 'axios',
  'nprogress': 'NProgress',
  'element-ui': 'ELEMENT',
  'echarts': 'echarts',
  'moment': 'moment'
}
// CDN外链，会插入到index.html中
const cdn = {
  // 开发环境
  dev: {
    css: [],
    js: []
  },
  // 生产环境
  build: {
    css: ['https://cdn.jsdelivr.net/npm/vant@2.12/lib/index.css'],
    js: [
      'https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js',
      'https://cdn.jsdelivr.net/npm/vue-router@3.1.5/dist/vue-router.min.js',
      'https://cdn.jsdelivr.net/npm/axios@0.19.2/dist/axios.min.js',
      'https://cdn.jsdelivr.net/npm/vuex@3.1.2/dist/vuex.min.js',
      'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js',
      'https://unpkg.com/element-ui/lib/index.js',
      'https://cdn.jsdelivr.net/npm/echarts@4.9.0/dist/echarts.min.js',
      'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js'
    ]
  }
}


module.exports = {
  publicPath: './',
  // 配置开发服务器
  //去除生产环境的productionSourceMap
  productionSourceMap: false,
  devServer: {
    port: 8000,
    // 配置端口号
    open: true,
    // 配置服务器自动打开浏览器
    https: false,
    // 是否开启https协议
    host: 'localhost',
    //设置主机名
    // proxy: {
    //     '/api': {
    //         target: 'http://120.53.31.103:84/api',
    //         changeOrigin: true, // 开启代理
    //         pathRewrite: { // 重写路径
    //             '^/api': ''
    //         }
    //     }
    // }

  },
  configureWebpack: config => {
    config.name = name

    // 为生产环境修改配置...
    if (isProduction) {
      // externals
      config.externals = externals
    }
    plugins: [
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        // test: /\.js$|\.html$|\.json$|\.css/,
        test: /\.js$|\.json$|\.css/,
        threshold: 10240, // 只有大小大于该值的资源会被处理
        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
        deleteOriginalAssets: true // 删除原文件
      })
    ],
      // config.plugins.push(
      //   new HashedModuleIdsPlugin()
      // ),
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              drop_console: true, //console
              pure_funcs: ['console.log'] //移除console
            }
          },
          parallel: true
        }),
      )

    // 公共代码抽离
    config.optimization = {
      splitChunks: {
        cacheGroups: {
          vendor: {
            chunks: 'all',
            test: /node_modules/,
            name: 'vendor',
            minChunks: 1,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 100
          },
          common: {
            chunks: 'all',
            test: /[\\/]src[\\/]js[\\/]/,
            name: 'common',
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 60
          },
          styles: {
            name: 'styles',
            test: /\.(sa|sc|c)ss$/,
            chunks: 'all',
            enforce: true
          },
          runtimeChunk: {
            name: 'manifest'
          }
        }
      }
    }

  },
  chainWebpack: config => {

    // ============注入cdn start============
    /**
     * 添加CDN参数到htmlWebpackPlugin配置中
     */
    config.plugin('html').tap(args => {
      if (isProduction) {
        args[0].cdn = cdn.build
      } else {
        args[0].cdn = cdn.dev
      }
      return args
    })

    // ============注入cdn start============

    // 添加别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('api', resolve('src/api'))
      .set('views', resolve('src/views'))
      .set('components', resolve('src/components'))
  }
}